package net.xdclass.controller;

import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import net.xdclass.service.NotifyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author:xuezhen
 * @CreateDate:2021/4/6 22:02
 * @UpdateUser:
 * @UpdateDate:
 * @UpdateRemark:
 * @Version:v2.0
 */
@Api(tags = "通知模块")
@RestController
@RequestMapping("api/user/v1")
@Slf4j
public class NotifyController {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private NotifyService notifyService;

    /**
     *临时使用10分钟有效，方便测试
     */
    private static final long CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10;

    /**
     * 获取图形验证码
     * @param request
     * @param response
     */
    @ApiOperation("获取图形验证码")
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){
        String text = captchaProducer.createText();
        redisTemplate.opsForValue().set(getCaptchaKey(request),text,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        log.info("图形验证码:{}",text);
        BufferedImage bufferedImage = captchaProducer.createImage(text);
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            ImageIO.write(bufferedImage, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("获取图形验证码失败:",e);
        }

    }


    /**
     * 发送验证码
     * @param to 发送的邮箱
     * @param captcha 检查验证码
     * @return
     */
    @ApiOperation("发送注册验证码")
    @GetMapping("send_code")
    public JsonData sendRegisterCode(@RequestParam(value = "to",required = true) String to,
                                     @RequestParam(value = "captcha",required = true) String captcha,
                                     HttpServletRequest request){
        // 匹配图形验证码是否正常
        String key = getCaptchaKey(request);
        String cacheCaptcha = redisTemplate.opsForValue().get(key);
        if(StringUtils.isNotBlank(cacheCaptcha) && StringUtils.isNotBlank(captcha) && cacheCaptcha.equalsIgnoreCase(captcha)){
            // 将验证码失效
            redisTemplate.delete(key);
            // 发送验证码
            return notifyService.sendCode(SendCodeEnum.USER_REGISTER, to);
        }else{
            // 验证码不一样
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }
    }

    private String getCaptchaKey(HttpServletRequest request) {
        String ipAddr = CommonUtil.getIpAddr(request);
        String header = request.getHeader("User-Agent");
        String key = CommonUtil.MD5(ipAddr + header);
        log.info("ip:{}",ipAddr);
        log.info("header:{}",header);
        log.info("验证码缓存key:{}",key);
        return key;
    }

}
